<template>
    <view class="content">
        <view class="head_bg">
            <view class="null"></view>
            <view class="back flex">
                <image @click="goBack" class="icon" src="https://cdn.oss.bon-top.cn/static_bc/images/back.png"></image>
                <text class="ft1">我的资料</text>
            </view>
        </view>
        <!-- <comHead :datas="datasObj"></comHead> -->
        <view class="mybox">
            <view class="userImg_box">
                <!-- <view class="yuan flex-center">
                    <image class="img avatar"
                        :src="userInfo.avatar || 'https://cdn.oss.bon-top.cn/static_bc/images/avtor.png'"
                        mode="scaleToFill" />
                    <image class="img_p" src="https://cdn.oss.bon-top.cn/static_bc/images/edit-icon.png"
                        mode="scaleToFill" />
                </view> -->
                <!-- <up-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="3" multiple
                    :maxCount="1" :previewFullImage="true"></up-upload>
                <view class="c-66 ft-24">点击编辑头像</view> -->



            </view>
            <view class="profile_box flex-c-center">
                <view class="profile_content">
                    <view class="bg_view flex-center">
                        <image class="img bd-r50c"
                            :src="userInfo?.avatar || 'https://cdn.oss.bon-top.cn/static_bc/images/avtor.png'"
                            mode="scaleToFill" @click="openImg(0, [userInfo.avatar])" />
                        <image class="img_p" src="https://cdn.oss.bon-top.cn/static_bc/images/edit-icon.png"
                            mode="aspectFit" @click="openUploadBtn(1)"></image>

                    </view>
                </view>
                <view class="profile_text ft-24 c-66" @click="openUploadBtn(1)">点击编辑头像</view>
            </view>
            <view class="list_view pd-30">
                <view class="list_view_model">
                    <view class="item pd-20 bd-r20" v-for="item in optionList" :key="item.key"
                        @click="item.url ? goPage(item.url) : changePup(item)">

                        <!-- 地区 -->
                        <picker v-if="item.key == 'city'" mode="region" :value="cityList" @change="bindRegionChange"
                            @bindcancel="bindcancel">
                            <view class="picker">
                                <view class="title ft-24 c-33 fw-800">{{ item.name }}</view>
                                <view class="text flex-bwt mt-10">
                                    <view class="ft-24 c-66">{{ item.data || '请选择' }}</view>

                                    <image class="icon_samll"
                                        src="https://cdn.oss.bon-top.cn/static_bc/images/icon_left.png"
                                        mode="scaleToFill" />

                                </view>
                            </view>
                        </picker>
                        <view class="picker" v-else>
                            <view class="title ft-24 c-33 fw-800">{{ item.name }}</view>
                            <view class="text flex-bwt mt-10">
                                <view class="ft-24 c-66">{{ item.data || '请选择' }}</view>
                                <!-- 地区 -->
                                <image class="icon_samll"
                                    src="https://cdn.oss.bon-top.cn/static_bc/images/icon_left.png"
                                    mode="scaleToFill" />

                            </view>
                        </view>
                    </view>
                </view>

                <view class="btn bd-r20" @click="getUserInfo(1)">保存</view>
            </view>

        </view>

        <!-- 性别 -->
        <u-action-sheet :actions="sexList" :show="showSex" @select="selectClick"></u-action-sheet>


    </view>
    <!-- 星座 -->
    <u-popup :show="showPup" @close="closePopup" :round="20">
        <!-- 弹窗标题与关闭按钮 -->
        <view class="popup-header">
            <text @click="closePopup">取消</text>
            <text @click="submit">确定</text>
        </view>
        <picker-view :indicator-style="`height:50px;`" :value="xzIndex" @change="bindPickerChange" class="picker-view">
            <picker-view-column style="height: 100%;">
                <view class="item" v-for="(item, index) in constellationList" :key="index">
                    {{ item }}</view>
            </picker-view-column></picker-view>
    </u-popup>
    <!-- 生日 -->
    <pickerTimePopup v-if="showSr" @getData="getData" :times="times"></pickerTimePopup>




</template>

<script setup lang="js">
import { onLoad } from '@dcloudio/uni-app';
import { nextTick, onMounted, reactive, ref } from 'vue';
import { utils } from "@/utils/utils.js";
import { api } from "@/utils/api.js";
import pickerTimePopup from '@/components/pickerTimePopup.vue';
let showPup = ref(false)
let optionList = reactive([{
    name: '昵称',
    key: 'nickname',
    url: '/subpackage/user/editNickName',
    data: ''
},
{
    name: '性别',
    key: 'sex',
    url: '',
},
{
    name: '星座',
    key: 'constellation',
    url: ''
},
{
    name: '生日',
    key: 'birthday',
    url: ''
},
{
    name: '所在城市',
    key: 'city',
    url: ''

},])

// 展示图片
const openImg = (index, imgList = []) => {
    uni.previewImage({
        current: index,
        urls: imgList
    });
}
// 新增图片
const openUploadBtn = async () => {
    // 图片
    const res = await uni.chooseImage({
        sizeType: ['original'], // iOS需保留原图避免压缩异常‌:ml-citation{ref="3" data="citationList"}
        sourceType: ['album', 'camera']
    })
    console.log('res', res)
    const result = await uploadFilePromise(res.tempFilePaths[0]);
    userInfo.value.avatar = result.url
    console.log('userInfo.value', userInfo.value.avatar)
};
const uploadFilePromise = (url) => {
    return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
            url: utils.domain+'/api/v1/button.uploadImage',
            filePath: url,
            name: 'image',
            fileType: 'image',
            formData: {
                app_id: utils.app_id,
                identity: utils.identity
            },
            header: {
                // 'content-type': 'multipart/form-data',
                'Authorization': utils.getToken()
            },
            success: (res) => {
                setTimeout(() => {
                    let data = JSON.parse(res.data)
                    resolve(data.data.info);
                }, 1000);
            },
        });
    });
};


let cityList = reactive([])
const bindRegionChange = (e) => {
    cityList = e.detail.value
    userInfo.value.city = cityList
    setOptionList()
}
const bindcancel = () => {
    cityList = []

}
const getData = (data) => {
    userInfo.value.birthday = data.time
    setOptionList()
}
// 关闭弹窗
const closePopup = () => {
    // props.show = false;
    showPup.value = false

};
// 确认选择
const submit = () => {
    const selected = constellationList[xzIndex.value];
    userInfo.value.constellation = selected
    setOptionList()
    closePopup();
};
// 返回键
const goBack = () => {
    uni.navigateBack(-1)
}
const bindPickerChange = (e) => {
    xzIndex.value = e.detail.value
}
const selectClick = (data) => {
    userInfo.value.sex = data.name
    showSex.value = !showSex.value

    setOptionList()
}
const showSex = ref(false)
const showXz = ref(false)
const showSr = ref(false)
const xzIndex = ref([5])
let times = reactive([])
const changePup = (data) => {
    if (data.key == 'sex') {
        showSex.value = !showSex.value
    }
    else if (data.key == 'constellation') {
        showPup.value = !showPup.value
        xzIndex.value = [constellationList.findIndex(f => f == userInfo.value.constellation) || 0]
    }
    else if (data.key == 'birthday') {
        showSr.value = !showSr.value
        times = userInfo.value.birthday.split('-')
    }
}
const goPage = (url) => {
    if (url !== '')
        uni.navigateTo({
            url: url,
            events: {
                // 监听子页面事件
                fromDetail: (data) => {
                    userInfo.value.nickname = data.nickname
                    setOptionList()

                }
            },
            success: (res) => {
                // 向子页面传递数据
                res.eventChannel.emit('toDetail', { userInfo: userInfo.value });
            }
        });


}
const userInfo = ref({})
let sexList = reactive([])
let constellationList = reactive([])
const getUserInfo = (isSub) => {
    let obj = {}
    if (!isSub) { obj['is_sub'] = isSub }
    else {
        obj = { ...userInfo.value }
        obj['is_sub'] = isSub

    }
    utils
        .request(
            api.editUser, obj,
            "post"
        )
        .then((res) => {

            nextTick(() => {
                userInfo.value = res.data?.info
                sexList = [{
                    name: '男',
                    id: 0
                }, {
                    name: '女',
                    id: 1
                }, {
                    name: '不显示',
                    id: 2
                },]
                constellationList = res.data?.options?.constellation_list
                if (!isSub) {
                    setOptionList()
                } else {
                    uni.showToast({
                        title: "保存成功~",
                        icon: 'none',
                        duration: 2000
                    })
                    // getUserInfo(0)
                    setTimeout(() => {

                        goBack()
                    }, 500)
                }
            })

        })
}
const setOptionList = () => {
    optionList.forEach((item) => {
        if (item.key == 'city') {
            let _data = userInfo.value[item.key] || []
            item.data = _data.length ? `${_data[0]} · ${_data[1]} · ${_data[2]}` : ''
        } else {
            item.data = userInfo.value[item.key]
        }

    })
}

onLoad(() => {
    getUserInfo(0)

})

</script>

<style lang="scss" scoped>
/* 选择器高度 */
// .picker-view {
//     height: 400rpx;
//     margin: 30rpx 0;
// }

// .picker-item {
//     line-height: 80rpx;
//     text-align: center;
// }

.picker-view {
    width: 100%;
    height: 400rpx;
    margin-top: 20rpx;

    .item {
        line-height: 100rpx;
        text-align: center;
    }
}

/* 头部与关闭按钮 */
.popup-header {
    display: flex;
    justify-content: space-between;
    padding: 20rpx 30rpx;
    border-bottom: 1px solid #eee;
    font-size: 28rpx;
}

:deep(.avatar-wrapper) {
    border: none !important;
    border-color: red !important;
    box-shadow: none;
}

.content {
    position: relative;
    height: 100vh;

    .mybox {
        background-color: #fff;
        border-radius: 40rpx 40rpx 0 0;
        position: absolute;
        width: 100%;
        min-height: 1300rpx;
        top: 240rpx;
        display: flex;
        flex-direction: column;

        // height:calc(100vh - 160rpx) ;
        .userImg_box {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-top: 60rpx;

            .avatar-wrapper {
                border: none !important;
                border-color: red !important;
                box-shadow: none;
            }

            .yuan {
                width: 136rpx;
                height: 136rpx;
                border: 2rpx solid #DBF046;
                border-radius: 50%;
                margin-bottom: 20rpx;
                position: relative;

            }

            .img_p {
                position: absolute;
                width: 36rpx;
                height: 36rpx;
                bottom: -2rpx;
                right: 2rpx;
            }

            .img {
                width: 120rpx;
                height: 120rpx;

            }
        }

        .profile_box {
            .bg_view {

                width: 136rpx;
                height: 136rpx;
                border: 2rpx solid #DBF046;
                border-radius: 50%;
                margin-bottom: 20rpx;
                position: relative;



                .img_p {
                    position: absolute;
                    width: 36rpx;
                    height: 36rpx;
                    bottom: -2rpx;
                    right: 2rpx;
                }

                .img {
                    width: 120rpx;
                    height: 120rpx;

                }
            }
        }

        .list_view {
            flex: 1;
            display: flex;
            flex-direction: column;
            // background-color: red;

            &_model {
                flex: 1;
            }

            .item {
                background-color: #F8F8F8;
                margin-bottom: 20rpx;

                .uni-input {
                    flex: 1;
                    background-color: red;

                }

                .uni-list-cell-db {
                    background-color: blue;
                    flex: 1;

                }
            }

            .btn {
                width: 100%;
                height: 78rpx;
                text-align: center;
                line-height: 78rpx;
                color: #DBF046;
                background-color: #333;
            }
        }
    }
}

.head_bg {
    width: 750rpx;
    height: 500rpx;
    background: linear-gradient(90deg, #dbf046 0%, #bfffbb 100%);
    border-radius: 0rpx 0rpx 0rpx 0rpx;
    background-image: url("https://cdn.oss.bon-top.cn/static_bc/images/mine_bg.png");
    background-size: 100% 100%;

    .null {
        width: 100%;
        height: 88rpx;
    }

    .back {
        height: 88rpx;
        width: 100%;

        .icon {
            width: 28rpx;
            height: 48rpx;
            margin-left: 30rpx;
            margin-right: 258rpx;
        }
    }
}
</style>